<template>
	<view>
		<u-navbar title="发红包"></u-navbar>
		<view class="tip">{{tip}}</view>
		<view class="u-flex u-m-x-30 u-m-t-20">
			<view class="type" @tap="changeType" v-if="btype=='群'">
				<text>{{type}}红包</text>
				<text class="iconfont icon-arrow-down u-m-l-10"></text>
			</view>
		</view>
		<view v-if="btype=='群'" class="group u-row-between u-m-t-20" :class="{error:count.error}" @tap="openCount">
			<view class="label u-flex">
				<image class="hb u-m-r-10" src="/static/images/red.png" mode="aspectFit"></image>
				<text class="u-font-32">红包个数</text>
			</view>
			<view class="value">
				<text class="u-font-32" :class="{'text-gray':!count.value}">{{count.value||'填写个数'}}</text>
				<text class="u-font-32 u-m-l-10">个</text>
			</view>
		</view>
		<view class="u-m-x-30 u-m-t-10 u-p-l-30" v-if="btype=='群'">
			<text class="u-font-24 text-grey">本群共{{userCount}}人</text>
		</view>
		<view v-if="type==TYPES.LUCK" class="group u-row-between u-m-t-30" :class="{error:amount.error}" @tap="openAmount">
			<view class="label u-flex">
				<view class="pin u-m-r-10">
					拼
				</view>
				<text class="u-font-32">总金额</text>
			</view>
			<view class="value">
				<text class="u-font-32" :class="{'text-gray':!amount.value}">¥{{amount.value||'0.00'}}</text>
			</view>
		</view>
		<view v-if="type==TYPES.ORDI" class="group u-row-between u-m-t-30" :class="{error:price.error}" @tap="openPrice">
			<view class="label u-flex">
				<text class="u-font-32">单个金额</text>
			</view>
			<view class="value">
				<text class="u-font-32" :class="{'text-gray':!price.value}">¥{{price.value||'0.00'}}</text>
			</view>
		</view>
		<view class="group u-m-t-30">
			<textarea class="textarea u-font-32" :auto-height="true" maxlength="24" placeholder-class="text-gray u-font-32" placeholder="恭喜发财，大吉大利" v-model="brief"></textarea>
		</view>
		<view v-if="type==TYPES.LUCK&&btype=='群'" @tap="chooseTarget" class="group u-m-t-30">
			<view class="u-font-32">
				指定成员
			</view>
			<view class="u-flex-1">
				
			</view>
			<view class="arrow">
				<text class="u-font-28" v-if="targets.length">已选{{targets.length}}人</text>
				<text class="u-font-28 text-grey" v-else>全体</text>
				<text class="u-m-l-10 text-gray iconfont icon-arrow-right"></text>
			</view>
		</view>
		<view class="total">
			<text class="rmb">¥</text>
			<text class="num">{{total}}</text>
		</view>
		<view class="submit" @tap="submit">
			发送红包
		</view>
		<u-keyboard mode="number" @change="countChange" @backspace="countBackspace" v-model="count.show" :mask="false" :show-tips="false" :dot-enabled="false"></u-keyboard>
		<u-keyboard mode="number" @change="priceChange" @backspace="priceBackspace" v-model="price.show" :mask="false" :show-tips="false"></u-keyboard>
		<u-keyboard mode="number" @change="amountChange" @backspace="amountBackspace" v-model="amount.show" :mask="false" :show-tips="false"></u-keyboard>
	</view>
</template>

<script>
	import { sendRed , TYPES} from "@/api/red.js"
	import {fetchGroupInfo} from "@/api/addr.js"
	import {mapGetters,mapMutations} from "vuex"
	import { delay } from "@/utils/util";
	export default {
		data() {
			return {
				TYPES,
				bid:'',
				btype:'',
				tip:'',
				type:'普通',
				userCount:99,
				count:{ 
					value:'',
					show:false,
					error:false
				}, 
				price:{ 
					value:'',
					show:false,
					error:false
				}, 
				amount:{ 
					value:'',
					show:false,
					error:false
				},
				targets:[],
				brief:'',
				lock:false
			};
		},
		computed:{
			...mapGetters('wallet',['assets']),
			...mapGetters('system',['redMax']),
			total(){
				if(this.type=='普通'){
					return (Number(this.price.value)*Number(this.count.value)).toFixed(2)
				}else if(this.type=='拼手气'){
					return Number(this.amount.value).toFixed(2)
				}
				return '0.00'
			}
		},
		onLoad({bid,btype}) {
			this.bid = bid
			this.btype = btype
			if(btype=='群'){
				this.type = '拼手气'
				fetchGroupInfo(this.bid).then(({userCount})=>{
					this.userCount = userCount
				})
				
			}
			if(btype == '用户'){
				this.count.value = 1
			}
		},
		methods:{
			...mapMutations('wallet',['setCatMoney']),
			async changeType(){
				const res = await new Promise((resolve,reject)=>{
					const opts = [{label:'拼手气红包',value:'拼手气'},{label:'普通红包',value:'普通'}]
					uni.showActionSheet({
						itemList:opts.map(({label})=>label),
						success({tapIndex}){
							resolve(opts[tapIndex])
						},
						fail:reject
					})
				})
				if(this.type==res.value){
					return
				}
				this.type = res.value
				const count = Number(this.count.value)
				if(res.value=='普通'){
					if(!count){
						this.price.value = this.amount.value
					}else if(this.amount.value){
						this.price.value = (Number(this.amount.value)/count).toFixed(2)
					}else{
						this.price.value =''
					}
				}else if(res.value=='拼手气'){
					if(!count){
						this.amount.value = this.price.value
					}else if(this.price.value){
						this.amount.value = (Number(this.price.value)*count).toFixed(2)
					}else{
						this.amount.value = ''
					}
				}
				this.check()
			},
			openCount(){
				this.count.show = true
				this.price.show = false
				this.amount.show = false
			},
			countChange(char){
				console.log(char)
				const value = this.count.value+char
				const reg = /^\d{1,3}$/
				if(!reg.test(value)){
					return 
				}
				this.count.value = value
				this.check()
			},
			countBackspace(){
				const value = this.count.value.slice(0,this.count.value.length-1)
				this.count.value = value
				this.check()
			},
			openPrice(){
				this.count.show = false
				this.price.show = true
				this.amount.show = false
			},
			priceChange(char){
				if(char=='.'&&!this.price.value){
					char = '0.'
				}
				const value = this.price.value+char
				const reg = /^\d{1,7}(\.\d{0,2})?$/
				if(!reg.test(value)){
					return 
				}
				this.price.value = value
				this.check()
			},
			priceBackspace(){
				const value = this.price.value.slice(0,this.price.value.length-1)
				this.price.value = value
				this.check()
			},
			openAmount(){
				this.count.show = false
				this.price.show = false
				this.amount.show = true
			},
			amountChange(char){
				if(char=='.'&&!this.amount.value){
					char = '0.'
				}
				const value = this.amount.value+char
				const reg = /^\d{1,10}(\.\d{0,2})?$/
				if(!reg.test(value)){
					return 
				}
				this.amount.value = value
				this.check()
			},
			amountBackspace(){
				const value = this.amount.value.slice(0,this.amount.value.length-1)
				this.amount.value = value
				this.check()
			},
			check(){
				this.tip = ''
				this.count.error = false
				this.price.error = false
				this.amount.error = false
				if(this.count.value){
					if(!Number(this.count.value)){
						this.tip = '请选择红包个数'
						this.count.error = true
					}
				}
				if(this.btype=='群'){
					if(Number(this.count.value)>this.userCount){
						this.tip = '红包个数不可超过当前群聊人数'
						this.count.error = true
					}
				}
				if(this.type=='普通'){
					const count = Number(this.count.value)
					const price = Number(this.price.value)
					if(count*price>this.redMax){
						this.tip = `总金额不可超过${this.redMax}元`
						this.count.error = true
					}
				}
				if(this.type=='拼手气'){
					const count = Number(this.count.value)
					const amount = Number(this.amount.value)
					if(amount>this.redMax){
						this.tip = `总金额不可超过${this.redMax}元`
						this.amount.error = true
						this.count.error = true
					}
					if(count&&amount){
						
						
						
						
						
						if(amount/count<0.01){
							this.tip = '单个红包金额不可低于0.01元'
							this.amount.error = true
							this.count.error = true
						}
					}
				}
			},
			async submit(){
				if(!Number(this.count.value)){
					this.tip = '请选择红包个数'
					this.count.error = true
					return
				}
				if(this.type=='普通'&&!Number(this.price.value)){
					this.tip = '未填写「单个金额」'
					this.price.error = true
					return
				}
				if(this.type=='拼手气'&&!Number(this.amount.value)){
					this.tip = '未填写「总金额」'
					this.amount.error = true
					return
				}
				this.check()
				if(!!this.tip){
					return
				}
				if(this.lock){
					return
				}
				if(this.assets.catMoney-this.total<0){
					return uni.showModal({
						content:'余额不足,是否前往充值?',
						confirmText:'前往',
						success({confirm}){
							if(!confirm){
								return
							}
							uni.navigateTo({
								url:'/pages/wallet/payment'
							})
						}
					})
				}
				try{
					this.lock = true
					const info  = {
						type:this.type,
						brief:this.brief||'恭喜发财，大吉大利',
						toBizType:this.btype,
						toBizId:this.bid,
						totalAmount:this.total*100,
						totalPacket:Number(this.count.value),
						ext:JSON.stringify({
							targets:this.targets.map(({userId})=>userId)
						})
					}
					const id = await sendRed(info)
					this.setCatMoney((this.assets.catMoney*100-Number(this.total)*100)/100)
					uni.$emit('redCreated',{id,...info})
					uni.navigateBack()
				}finally{
					await delay(500)
					this.lock = false
				}
			},
			chooseTarget(){
				uni.navigateTo({
					url:`/pages/group/member/choose?id=${this.bid}`,
					events:{
						confirm:(chosen)=>{
							this.targets = chosen
						}
					},
					success:({eventChannel})=>{
						eventChannel.emit('initChosen',this.targets)
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.tip{
		text-align: center;
		background-color: #cb9801;
		color: #ffffff;
	}
	.type{
		font-size: 30rpx;
		color: #e5b728;
	}
	.group{
		margin-left: 30rpx;
		margin-right: 30rpx;
		display: flex;
		align-items: center;
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 30rpx;
		&.error{
			color: #ff3914;
		}
		.hb{
			width: 44rpx;
			height: 44rpx;
		}
		.pin{
			width: 44rpx;
			height: 44rpx;
			font-size: 28rpx;
			text-align: center;
			line-height: 44rpx;
			border-radius: 6rpx;
			background-color: #e5b728;
			color: #ffffff;
		}
	}
	.total{
		text-align: center;
		margin-top: 50rpx;
		.rmb{
			vertical-align: middle;
			font-size: 50rpx;
		}
		.num{
			vertical-align: middle;
			font-size: 70rpx;
			margin-left: 10rpx;
		}
	}
	.textarea{
		width: 100%;
		max-height: 80rpx;
		overflow: scroll;
	}
	.submit{
		padding: 24rpx 0;
		background-color: #ff3914;
		color: #ffffff;
		font-size: 34rpx;
		font-weight: bold;
		border-radius: 20rpx;
		text-align: center;
		margin: 30rpx 200rpx 0;
	}
</style>
